package cmd

import (
	"context"
	"fmt"
	"strings"
	"time"

	pb3 "github.com/cheggaaa/pb/v3"

	pb "gitee.com/zfd81/dbrs/proto/dbrspb"

	"github.com/spf13/viper"

	"github.com/spf13/cobra"
)

func NewSyncCommand() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "sync <definition file>",
		Short: "Syncs data",
		Run:   SyncCommandFunc,
	}
	return cmd
}

func SyncCommandFunc(cmd *cobra.Command, args []string) {
	if len(args) != 1 {
		ExitWithError(ExitBadArgs, fmt.Errorf("sync cmd requires definition file path as its argument"))
	}
	startTime := time.Now() //开始时间
	path := args[0]
	var define Definition
	viper.SetConfigFile(path)
	viper.SetConfigType("yaml")
	err := viper.ReadInConfig()
	if err != nil {
		ExitWithError(ExitBadArgs, fmt.Errorf("Definition file error: %v", err))
	}
	err = viper.Unmarshal(&define)
	if err != nil {
		panic(fmt.Errorf("Fatal error when reading %s config, unable to decode into struct, %v", path, err))
	}

	token, err := getToken()
	if err != nil {
		ExitWithError(ExitError, err)
	}

	if strings.TrimSpace(define.From.Database) == "" {
		ExitWithError(ExitBadArgs, fmt.Errorf("Source database cannot be empty"))
	}

	if strings.TrimSpace(define.From.Sign) == "" {
		ExitWithError(ExitBadArgs, fmt.Errorf("Source sign cannot be empty"))
	}

	if strings.TrimSpace(define.From.Sql) == "" {
		ExitWithError(ExitBadArgs, fmt.Errorf("Source sql cannot be empty"))
	}

	if strings.TrimSpace(define.To.Database) == "" {
		ExitWithError(ExitBadArgs, fmt.Errorf("The target database cannot be empty"))
	}

	if strings.TrimSpace(define.To.Table) == "" {
		ExitWithError(ExitBadArgs, fmt.Errorf("The target table cannot be empty"))
	}

	request := &pb.SyncRequest{
		Token:   token,
		FromDb:  define.From.Database,
		Sign:    define.From.Sign,
		Sql:     define.From.Sql,
		ToDb:    define.To.Database,
		ToTable: define.To.Table,
		User:    define.User,
	}
	client, err := BrokerSystemClient()
	if err != nil {
		ExitWithError(ExitBadConnection, err)
	}

	count := 100
	cnt := 0
	bar := pb3.Simple.Start(count)
	go func() {
		for i := 0; i < count-1; i++ {
			bar.Increment()
			cnt++
			time.Sleep(200 * time.Millisecond)
		}
	}()

	resp, err := client.Sync(context.Background(), request)
	if err != nil {
		ExitWithError(ExitBadFeature, err)
	}

	bar.Add(count - cnt)
	bar.Finish()

	fmt.Printf("Record Count: %d\n", resp.Cnt)
	fmt.Printf("Elapsed time: %v\n", time.Since(startTime))
}

type From struct {
	Database string `mapstructure:"database"`
	Sign     string `mapstructure:"sign"`
	Sql      string `mapstructure:"sql"`
}

type To struct {
	Database string `mapstructure:"database"`
	Table    string `mapstructure:"table"`
}

type Definition struct {
	From `mapstructure:"from"`
	To   `mapstructure:"to"`
	User string `mapstructure:"user"`
}
